#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    //从命令行参数拿到ip地址和端口号
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport); //转换网络字节序
    server.sin_addr.s_addr = inet_addr(serverip.c_str());//转换网络字节序
    // 1. socket拿到网络描述符
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);


    socklen_t len = sizeof(server);
    string message;
    char buffer[1024];
    while (true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);
        //2. 向服务器发送信息
        sendto(sockfd, message.c_str(), message.size(), 
        0, (struct sockaddr *)&server, len);
        
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        //3. 打印来自服务器的信息
        recvfrom(sockfd, buffer, 1023, 0, (struct sockaddr*)&temp, &len);
        cout << buffer << endl;
        
    }

    close(sockfd);//关闭文件描述符
    return 0;
}